package com.springboot.dubbo.consumer;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.fastjson.JSONObject;
import com.springboot.common.util.StringUtil;
import com.springboot.dubbo.cluster.CustomClusterInvoker;
import com.springboot.dubbo.param.request.QueryUserParam;
import com.springboot.dubbo.param.request.UserInParam;
import com.springboot.dubbo.param.response.UserOutParam;
import com.springboot.dubbo.service.UserService;
import com.springboot.zookeeper.ZookeeperConfigService;

import lombok.extern.log4j.Log4j2;

/**
 * 用户消费者
 *
 * @author supu
 * @create 2019-01-04 10:29
 **/
@Log4j2
@Service
public class UserConsumer {
    @Autowired
    private UserService userService;
    @Autowired
    private ZookeeperConfigService zookeeperConfigService;

    public List<UserOutParam> getUsers(Integer id) {
        QueryUserParam param = new QueryUserParam();
        param.setId(id);
        log.warn("userServiceProvider selectUsers 请求参数：{}", param);
        String host = getHostByUserId(id);
        if (StringUtil.isNotEmpty(host)) {
            RpcContext.getContext().setAttachment(CustomClusterInvoker.BIND_IP_KEY, host);
        }
        List<UserOutParam> userList = userService.selectUsers(param);
        log.warn("userServiceProvider selectUsers 请求结果：{}", JSONObject.toJSONString(userList));
        return userList;
    }

    public void updateUser(Integer id) {
        UserInParam user = new UserInParam();
        user.setId(id);
        user.setName("oo"+id);
        user.setSex((byte) 1);
        log.warn("userServiceProvider updateUser 请求参数: {}", user);
        userService.updateUser(user);
    }

    public void saveUser() {
        UserInParam user = new UserInParam();
        user.setName("00");
        user.setSex((byte) 1);
        log.warn("userServiceProvider saveUser 请求参数: {}", user);
        userService.saveUsers(user);
    }

    private String getHostByUserId(Integer id) {
        String id2Host = zookeeperConfigService.getValue("id_to_host");
        if (StringUtil.isEmpty(id2Host) || id == null) {
            return null;
        }
        Map<String, String> hostMap = JSONObject.parseObject(id2Host, Map.class);
        if (id % 2 == 0) {
            // 偶数
            return hostMap.get("evenNumber");
        }

        // 奇数
        return hostMap.get("oddNumber");
    }
}
